from flask import Flask, render_template, redirect, url_for, flash
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import IntegerField, StringField, SubmitField
from wtforms.validators import DataRequired 
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'test'  
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:%40Wxl123456@localhost:3306/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True  
db = SQLAlchemy(app)
bootstrap = Bootstrap(app)

class Student_Info(db.Model):
    __tablename__ = 'student_info'  # MySQL表名
    student_id = db.Column(db.Integer, primary_key=True)  # 学生ID（主键，唯一）
    student_name = db.Column(db.Text, nullable=False)  # 学生姓名（不能为空）


class NameForm(FlaskForm):
    id = IntegerField('学生ID', validators=[DataRequired()])
    name = StringField('学生姓名', validators=[DataRequired()])
    submit = SubmitField('提交')
class EditForm(NameForm):
    submit = SubmitField('保存修改')

class DeleteForm(FlaskForm):
    submit = SubmitField('确认删除')

@app.route("/", methods=['GET', 'POST'])
def index():
    delete_form = DeleteForm()  
 
    studs = Student_Info.query.all()
    return render_template('index.html', studs=studs, delete_form=delete_form)

@app.route("/new", methods=['GET', 'POST'])
def new_stud():
    form = NameForm()
    if form.validate_on_submit():
        new_id = form.id.data
        new_name = form.name.data
        if Student_Info.query.filter_by(student_id=new_id).first():
            flash('该学生ID已存在！换个ID试试～')  
            return redirect(url_for('new_stud'))  # 回到新增页
        new_stud = Student_Info(student_id=new_id, student_name=new_name)
        db.session.add(new_stud)  
        db.session.commit()       
        flash('新增学生成功！')     # 弹出成功提示
        return redirect(url_for('index'))  # 跳回首页
    return render_template("new_student.html", form=form)
@app.route("/edit/<int:stu_id>", methods=["GET", "POST"])
def edit_stud(stu_id):
    form = EditForm()
    stud = Student_Info.query.get_or_404(stu_id)
    
    if form.validate_on_submit():
        stud.student_id = form.id.data
        stud.student_name = form.name.data
        db.session.commit()  
        flash('学生信息修改成功！')
        return redirect(url_for('index'))
    form.id.data = stud.student_id
    form.name.data = stud.student_name
    return render_template('edit_info.html', form=form)
@app.route("/delete/<int:stud_id>", methods=["POST"])  # 只允许POST请求（更安全）
def del_stud(stud_id):
    form = DeleteForm()
    if form.validate_on_submit():                        
        stud = Student_Info.query.get_or_404(stud_id)
        db.session.delete(stud)  
        db.session.commit()     
        flash(f'已删除学生：{stud.student_name}')
    return redirect(url_for('index'))

if __name__ == '__main__':
    with app.app_context():
        db.create_all()  
    app.run(debug=True)  